#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "InetAddr.hpp"
#include "Log.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " server_ip server_port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error " << std::endl;
        exit(2);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }

    while (true)
    {
        std::cout << "Please Enter# ";
        std::string outstring;
        std::getline(std::cin, outstring);
        ssize_t n = ::send(sockfd, outstring.c_str(), outstring.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024] = {0};
            ssize_t m = recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);
            std::cout<< inbuffer <<std::endl;
        }
        else
        {
            break;
        }
    }

    return 0;
}